def rec_max(list):
    if len(list) == 1:
        return list[0]
    else:
        return max(list[0], rec_max(list[1:]))

def add_all(entries):
    result = 0.0
    for entry in entries:
        result += entry

    return result

def average_all(li):
    return add_all(li)/len(li)

def merge_moms(moms, result = None):
    if result is None:
        result = [[[None for i in n] for n in l] for l in moms[0]]

    for layer in xrange(len(moms[0])):
        for n in xrange(len(moms[0][layer])):
            for i in xrange(len(moms[0][layer][n])):
                result[layer][n][i] = average_all([mom[layer][n][i] for mom in moms])

    return result

def maxindex(output, max = 0, ignore_indices = set()):
    while max in ignore_indices:
        max += 1
    if max >= len(output):
        raise IndexError, "Either empty output or no not-to-be-ignored entry."
    else:
        for i in xrange(max, len(output)):
            if output[i] >= output[max] and not i in ignore_indices:
                max = i
        return max

import math

MAX_DIFFVAL = 1000.0

def pick_letter(alphabet, directions, output):
    min_diff = MAX_DIFFVAL
    letter = None

    for a in xrange(len(alphabet)):
        norm_diff = 0.0

        for i in xrange(len(output)):
            diff = directions[a][i] - output[i]
            norm_diff += diff * diff
        norm_diff = math.sqrt(norm_diff)

        if norm_diff < min_diff:
            letter = alphabet[a]
            min_diff = norm_diff

    return letter

